// 灵感首页
//  MZY_InspirationViewController.m
//  FullHouse
//
//  Created by dllo on 16/1/15.
//  Copyright © 2016年 yy. All rights reserved.
//

#import "MZY_InspirationViewController.h"
#import "NetworkingTool.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "MZY_AlbumCell.h"
#import "MZY_PictureModel.h"
#import "MZY_AlbumModel.h"
#import "MZY_TitleViewController.h"
#import "MZY_DisplayCollectionViewCell.h"
#import "MZY_commentViewController.h"
#import "MZY_albumViewController.h"
#import "MJRefresh.h"
#import "DataBaseHandle.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
#define HORIZONTAL [UIScreen mainScreen].bounds.size.width / 414
#define VERTICAL [UIScreen mainScreen].bounds.size.height / 736

@interface MZY_InspirationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,MZY_TitleViewControllerDelegate>

@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)UICollectionView *LeftLineCollectionView;
@property(nonatomic, retain)NSMutableArray *pictureArr;
@property(nonatomic, retain)UITableView *RightLineTableView;
@property(nonatomic, retain)NSMutableArray *albumArr;
@property(nonatomic, retain)UIButton *pictureButton;
@property(nonatomic, retain)UIButton *albumButton;
@property(nonatomic, assign)BOOL isPicture;
@property(nonatomic, retain)MBProgressHUD *hud;
@property(nonatomic, assign)NSInteger num;
@property(nonatomic, assign)NSInteger count;
@property(nonatomic, retain)NSString *tags;

// 标题
@property(nonatomic, retain)UILabel *titleLabel;

@end

@implementation MZY_InspirationViewController

- (void)dealloc
{
    [self.scrollView release];
    [self.LeftLineCollectionView release];
    [self.pictureArr release];
    [self.RightLineTableView release];
    [self.albumArr release];
    [self.pictureButton release];
    [self.albumButton release];
    [self.hud release];
    [self.tags release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createData];
    [self createView];
}

#pragma mark 获取数据
- (void)createData{
    NSString *url = [NSString stringWithFormat:@"http://api.meilijia.com/app/idea_photos?page=1&%@",self.tags];
    [NetworkingTool networkingWithStrURL:url type:GETType bodyStr:nil block:^(id result) {
            self.pictureArr = [NSMutableArray array];
            for (NSDictionary *temp in result[@"data"][@"idea_photos"][@"photos"]) {
                MZY_PictureModel *pic = [[MZY_PictureModel alloc]init];
                [pic setValuesForKeysWithDictionary:temp];
                [self.pictureArr addObject:pic];
                [pic release];
            }
            [self.LeftLineCollectionView reloadData];
            self.hud.hidden = YES;
        }];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://api.meilijia.com/app/idea_collections?page=1&%@",self.tags];
    [NetworkingTool networkingWithStrURL:urlStr type:GETType bodyStr:nil block:^(id result) {
            self.albumArr = [NSMutableArray array];
            for (NSDictionary *temp in result[@"data"][@"idea_collections"][@"collections"]) {
            MZY_AlbumModel *album = [[MZY_AlbumModel alloc]init];
            [album setValuesForKeysWithDictionary:temp];
            [self.albumArr addObject:album];
            [album release];
        }
        [self.RightLineTableView reloadData];
    }];
}

#pragma mark 加载数据
- (void)loadData{
    NSString *strC = [NSString stringWithFormat:@"http://api.meilijia.com/app/idea_photos?page=%d&%@",self.num ++,self.tags];
    [NetworkingTool networkingWithStrURL:strC type:GETType bodyStr:nil block:^(id result) {
        for (NSDictionary *temp in result[@"data"][@"idea_photos"][@"photos"]) {
            MZY_PictureModel *pic = [[MZY_PictureModel alloc]init];
            [pic setValuesForKeysWithDictionary:temp];
            [self.pictureArr addObject:pic];
            [pic release];
        }
        [self.LeftLineCollectionView reloadData];
        self.hud.hidden = YES;
    }];
    NSString *strT = [NSString stringWithFormat:@"http://api.meilijia.com/app/idea_collections?page=%d&%@",self.count ++,self.tags];
    [NetworkingTool networkingWithStrURL:strT type:GETType bodyStr:nil block:^(id result) {
        for (NSDictionary *temp in result[@"data"][@"idea_collections"][@"collections"]) {
            MZY_AlbumModel *album = [[MZY_AlbumModel alloc]init];
            [album setValuesForKeysWithDictionary:temp];
            [self.albumArr addObject:album];
            [album release];
        }
        [self.RightLineTableView reloadData];
    }];
}

- (void)createView{
    
    self.view.backgroundColor = [UIColor cyanColor];
    
    // 自定义标题
    UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    titleButton.frame = CGRectMake(0, 0, 60, 20);
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 20)];
    self.titleLabel.text = @"热门";
    self.titleLabel.textColor = [UIColor orangeColor];
    [titleButton addSubview:self.titleLabel];
    [self.titleLabel release];
    UIImageView *titleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 0, 20, 20)];
    titleImageView.image = [UIImage imageNamed:@"iconfont-shang.png"];
    [titleButton addSubview:titleImageView];
    [titleImageView release];
    [titleButton addTarget:self action:@selector(titleAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleButton;
    
    // 分隔线
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
    textField.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:textField];
    [textField release];
    
    // 创建一个空白"view"
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, WIDTH, 30 * VERTICAL)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    [topView release];
    
    self.pictureButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.pictureButton.frame = CGRectMake(160 * HORIZONTAL, 0, 40 * HORIZONTAL, 30 * VERTICAL);
    [self.pictureButton setTitle:@"图片" forState:UIControlStateNormal];
    [self.pictureButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [topView addSubview:self.pictureButton];
    [self.pictureButton addTarget:self action:@selector(pictureAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.albumButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.albumButton.frame = CGRectMake(220 * HORIZONTAL, 0, 40 * HORIZONTAL, 30 * VERTICAL);
    [self.albumButton setTitle:@"画册" forState:UIControlStateNormal];
    [self.albumButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [topView addSubview:self.albumButton];
    [self.albumButton addTarget:self action:@selector(albumAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 31 * VERTICAL, WIDTH  , HEIGHT - 64 - 49)];
    self.scrollView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:self.scrollView];
    self.scrollView.contentOffset = CGPointMake(0, 0);
    self.scrollView.contentSize = CGSizeMake(WIDTH * 2, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    [self.scrollView release];
    
    // 创建一个左边的"collectionView"
    UICollectionViewFlowLayout *rowFlowLayout = [[UICollectionViewFlowLayout alloc]init];
    rowFlowLayout.itemSize = CGSizeMake(190 * HORIZONTAL, 215 * VERTICAL);
    rowFlowLayout.minimumInteritemSpacing = 10 * HORIZONTAL;
    rowFlowLayout.minimumLineSpacing = 10 * VERTICAL;
    rowFlowLayout.sectionInset = UIEdgeInsetsMake(10 * HORIZONTAL, 10 * HORIZONTAL, 10 * HORIZONTAL, 10 * HORIZONTAL);
    
    self.LeftLineCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49 - 64 - 31) collectionViewLayout:rowFlowLayout];
    self.LeftLineCollectionView.scrollEnabled = YES;
    self.LeftLineCollectionView.backgroundColor = [UIColor cyanColor];
    [self.scrollView addSubview:self.LeftLineCollectionView];
    self.LeftLineCollectionView.dataSource = self;
    self.LeftLineCollectionView.delegate = self;
    [self.LeftLineCollectionView registerClass:[MZY_DisplayCollectionViewCell class] forCellWithReuseIdentifier:@"left"];
    [self.LeftLineCollectionView release];
    
    // 创建一个右边的"tableView"
    self.RightLineTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, 0, WIDTH, HEIGHT - 49 - 64 - 31) style:UITableViewStylePlain];
    [self.scrollView addSubview:self.RightLineTableView];
    self.RightLineTableView.backgroundColor = [UIColor cyanColor];
    self.RightLineTableView.rowHeight = 160 * HORIZONTAL;
    self.RightLineTableView.delegate = self;
    self.RightLineTableView.dataSource = self;
    [self.RightLineTableView registerClass:[MZY_AlbumCell class] forCellReuseIdentifier:@"right"];
    [self.RightLineTableView release];
    
    // 加载动画
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    self.isPicture = NO;
    
    self.num = 2;
    self.count = 2;
    self.tags = @"tags=null";
    // 下拉刷新
    [self.LeftLineCollectionView addHeaderWithTarget:self action:@selector(refreshView)];
    self.LeftLineCollectionView.headerRefreshingText = @"松开即可刷新";
    [self.RightLineTableView addHeaderWithTarget:self action:@selector(refreshView)];
    self.RightLineTableView.headerRefreshingText = @"松开即可刷新";
    // 上拉加载
    [self.LeftLineCollectionView addFooterWithTarget:self action:@selector(loadDataView)];
    self.LeftLineCollectionView.footerRefreshingText = @"请耐心等待,正在为您加载...";
    [self.RightLineTableView addFooterWithTarget:self action:@selector(loadDataView)];
    self.RightLineTableView.footerRefreshingText = @"请耐心等待,正在为您加载...";
}

#pragma mark 执行刷新
- (void)refreshView{
    [self createData];
    [self.LeftLineCollectionView reloadData];
    [self.RightLineTableView reloadData];
    [self.LeftLineCollectionView headerEndRefreshing];
    [self.RightLineTableView headerEndRefreshing];
}

#pragma mark 执行加载
- (void)loadDataView{
    [self loadData];
    [self.LeftLineCollectionView reloadData];
    [self.RightLineTableView reloadData];
    [self.LeftLineCollectionView footerEndRefreshing];
    [self.RightLineTableView footerEndRefreshing];
}

#pragma mark 右边"tableView"的第一个必须执行的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.albumArr.count;
}

#pragma mark 右边"tableView"的第二个必须执行的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MZY_AlbumModel *album = self.albumArr[indexPath.row];
    MZY_AlbumCell *cell = [tableView dequeueReusableCellWithIdentifier:@"right" forIndexPath:indexPath];
    cell.selectionStyle  = UITableViewCellEditingStyleNone;
    [cell.bigImageView sd_setImageWithURL:[NSURL URLWithString:album.cover_pic]];
    [cell.topImageView sd_setImageWithURL:[NSURL URLWithString:album.items[0][@"pic"]]];
    [cell.bottomImageView sd_setImageWithURL:[NSURL URLWithString:album.items[1][@"pic"]]];
    cell.titleLabel.text = album.title;
    cell.titleLabel.font = [UIFont systemFontOfSize:15 * HORIZONTAL];
    cell.titleLabel.numberOfLines = 0;
    [cell.titleLabel sizeToFit];
    cell.authorLabel.textColor = [UIColor lightGrayColor];
    [cell.likeButton setImage:[UIImage imageNamed:@"zan.png"] forState:UIControlStateNormal];
    [cell.likeButton addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.likeCountLabel.text = album.liked_count;
    [cell.authorImageView sd_setImageWithURL:[NSURL URLWithString:album.author_face]];
    cell.authorImageView.layer.cornerRadius = 20 * HORIZONTAL;
    cell.authorImageView.layer.masksToBounds = YES;
    cell.authorLabel.text = album.author_nick;
    cell.authorLabel.font = [UIFont systemFontOfSize:15 * HORIZONTAL];
    return cell;
}

#pragma mark 右边"tableView"的点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.hidesBottomBarWhenPushed = YES;
    MZY_albumViewController *albumVC = [[MZY_albumViewController alloc]init];
    [self.navigationController pushViewController:albumVC animated:YES];
    MZY_AlbumModel *album = self.albumArr[indexPath.row];
    albumVC.idStr = album.col_id;
    albumVC.picStr = album.cover_pic;
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark 左边"collectionView"的第一个必须执行的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.pictureArr.count;
}

#pragma mark 左边"collectionView"的第二个必须执行的方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MZY_DisplayCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"left" forIndexPath:indexPath];
    MZY_PictureModel *pic = self.pictureArr[indexPath.row];
    [cell.pictureImageView sd_setImageWithURL:[NSURL URLWithString:pic.pic]];
    cell.pic = pic;
    
    SelectType type = [[DataBaseHandle shareDB] colIsInTable:pic];
    if (type == InTable) {
        [cell.likeButton setImage:[UIImage imageNamed:@"iconfont-xin2.png"] forState:UIControlStateNormal];
    }else if (type == NotInTable){
        [cell.likeButton setImage:[UIImage imageNamed:@"iconfont-xin.png"] forState:UIControlStateNormal];
    }else{
        NSLog(@"查询失败");
    }

    [cell.addButton setImage:[UIImage imageNamed:@"iconfont-jia.png"] forState:UIControlStateNormal];
    [cell.addButton addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.likeCountLabel.text = pic.col_count;
    return cell;
}

#pragma mark 左边的"collectionView"的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.hidesBottomBarWhenPushed = YES;
    MZY_PictureModel *picture = self.pictureArr[indexPath.row];
    MZY_commentViewController *commentVC = [[MZY_commentViewController alloc]init];
    [self.navigationController pushViewController:commentVC animated:YES];
    commentVC.picStr = picture.pic_detail;
    commentVC.idStr = picture.photo_id;
    commentVC.addCount = picture.col_count;
    commentVC.commentCount = picture.comment_count;
    commentVC.face = picture.author_face;
    commentVC.nick = picture.author_nick;
    commentVC.name = picture.col_name;
    commentVC.firstphoto = picture.col_photos[0][@"pic"];
    commentVC.secondphoto= picture.col_photos[1][@"pic"];
    commentVC.thirdphoto = picture.col_photos[2][@"pic"];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark 图片"button"的点击方法
- (void)pictureAction:(UIButton *)button{
    if (self.isPicture == NO) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
        [self.pictureButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [self.albumButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    else{
        [self.pictureButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [self.albumButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }
}

#pragma mark 画册"button"的点击方法
- (void)albumAction:(UIButton *)button{
    if (self.isPicture == NO) {
        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        [self.pictureButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [self.albumButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }
    else{
        [self.pictureButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [self.albumButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }
}

#pragma mark 根据偏移量切换"button"方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (self.scrollView.contentOffset.x / WIDTH == 0) {
        [self.pictureButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [self.albumButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }else{
        [self.pictureButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [self.albumButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    }
}

#pragma mark 标题"button"的点击方法
- (void)titleAction:(UIButton *)button{
    self.hidesBottomBarWhenPushed = YES;
    MZY_TitleViewController *titleVC = [[MZY_TitleViewController alloc]init];
    [self.navigationController pushViewController:titleVC animated:YES];
    void (^block)(NSString *) = ^(NSString *str){
        self.titleLabel.text = str;
    };
    titleVC.block = block;
    
    titleVC.delegate = self;
    
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark 协议传值的执行方法
- (void)bringStr:(NSString *)str{
    self.tags = str;
    NSString *urlStr = [NSString stringWithFormat:@"http://api.meilijia.com/app/idea_photos?page=1&%@",str];
    [NetworkingTool networkingWithStrURL:urlStr type:GETType bodyStr:nil block:^(id result) {
        self.pictureArr = [NSMutableArray array];
        for (NSDictionary *temp in result[@"data"][@"idea_photos"][@"photos"]) {
            MZY_PictureModel *pic = [[MZY_PictureModel alloc]init];
            [pic setValuesForKeysWithDictionary:temp];
            [self.pictureArr addObject:pic];
            [pic release];
        }
        [self.LeftLineCollectionView reloadData];
        self.hud.hidden = YES;
    }];
    
    NSString *url = [NSString stringWithFormat:@"http://api.meilijia.com/app/idea_collections?page=1&%@",str];
    [NetworkingTool networkingWithStrURL:url type:GETType bodyStr:nil block:^(id result) {
        self.albumArr = [NSMutableArray array];
        for (NSDictionary *temp in result[@"data"][@"idea_collections"][@"collections"]) {
            MZY_AlbumModel *album = [[MZY_AlbumModel alloc]init];
            [album setValuesForKeysWithDictionary:temp];
            [self.albumArr addObject:album];
            [album release];
        }
        [self.RightLineTableView reloadData];
    }];

}

#pragma mark 添加''"button"的点击方法
- (void)addAction:(UIButton *)button{
    
}

#pragma mark 赞"button"的点击方法
- (void)zanAction:(UIButton *)button{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
